package com.cjl.web.backend;


import com.cjl.entity.EbProduct;
import com.cjl.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Controller //标记为web服务员；
@RequestMapping("/product")  //工号；
public class ProductController {

    @Autowired    //spring会将ProductService对象创建出来
    private ProductService productService;

    /**
     * 将数据放到model中，将页面放到view中
     * spring mvc---将model渲染到view中
     * list ---分页请求数据
     *
     * @return
     */

    @RequestMapping("/list")
    /**
     * 获取用户分页信息
     * page是请求参数
     */
    public String list(Model model,
                       @RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "6") int pageSize) {
        System.out.println("start service....." + page);
        //请求service层获取用户的分页数据
        final List<EbProduct> productList = productService.listByPage(page, pageSize);
        final Integer totalPage = productService.findTotalPage(pageSize);
        //传递model（数据）和view视图（jsp）
        //将model和jsp整合  key-value 键值对
        model.addAttribute("productList", productList);
        //model绑定当前总页数
        model.addAttribute("totalPage", totalPage);
        //model绑定当前页
        model.addAttribute("currPage", page);

        return "manage/product";//视图 manage/user.jsp通过进行获取数据
    }

    @RequestMapping("/to_save")
    public String toSave() {
        return "manage/product-add";
    }

    @RequestMapping("/save")
    public String save(EbProduct ebProduct, MultipartFile pictureFile, HttpServletRequest request) {
        String originFile = pictureFile.getOriginalFilename();
        System.out.println("pictureFile===" + originFile);
        //2.生产新的文件名
        String newFileName = UUID.randomUUID().toString() + originFile.substring(originFile.indexOf("."));
        //完成上传
        //3.设置上传文件名给ebProduct
        ebProduct.setEpFileName(newFileName);
        //服务器的路径
        String path = request.getServletContext().getRealPath("/")+"WEB-INF/images/product/";
        System.out.println("path===>" + path);
        //String path = "F:/easybuy-chl/src/main/webapp/WEB-INF/images/product/";
        File uploadPic = new File(path + newFileName);
        System.out.println(newFileName);
        try {
            if (!uploadPic.exists()) {
                uploadPic.mkdirs();
            }
            //向磁盘写文件
            pictureFile.transferTo(uploadPic);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("ebProduct===" + ebProduct);
        //result返回受影响行数
        Integer result = productService.save(ebProduct);
        System.out.println("result ==>" + result);
        //根据result的结果>0跳转页面
        if (result <= 0) {
            //TODO 添加失败后的处理 1.提示失败 2.抛出异常
            return "manage/result-error";
        }
        return "manage/manage-result";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        int result = productService.delete(id);
        if (result == 0) {
        }
        return "manage/manage-result";
    }

    @RequestMapping("/to_edit")
    public String toEdit(Model model, @RequestParam("epId") int epId) {
        System.out.println("点击跳转正在进行...epId===" + epId);
        //调用Service层的方法查询点击的用户的所有信息
        EbProduct ebProduct = productService.selectOne(epId);
        //指定model和jsp
        model.addAttribute("ebProduct", ebProduct);
        return "manage/product-modify";
    }

    @RequestMapping("/edit")
    public String edit(EbProduct ebProduct, MultipartFile pictureFile, HttpServletRequest request) {
        String originFile = pictureFile.getOriginalFilename();
        System.out.println("pictureFile===" + originFile);
        //2.生产新的文件名
        String newFileName = UUID.randomUUID().toString() + originFile.substring(originFile.indexOf("."));
        //完成上传
        //3.设置上传文件名给ebProduct
        ebProduct.setEpFileName(newFileName);
        //服务器的路径
        String path = request.getServletContext().getRealPath("/") + "WEB-INF/images/product/";
        System.out.println("path===>" + path);
        //String path = "F:/easybuy-chl/src/main/webapp/WEB-INF/images/product/";
        File uploadPic = new File(path + newFileName);
        System.out.println(newFileName);
        try {
            if (!uploadPic.exists()) {
                uploadPic.mkdirs();
            }
            //向磁盘写文件
            pictureFile.transferTo(uploadPic);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("ebProduct===" + ebProduct);
        Integer result = productService.updateById(ebProduct);
        System.out.println("result ==>" + result);
        if (result <= 0) {
            //TODO 添加失败后的处理 1.提示失败 2.抛出异常
            return "manage/result-error";
        }
        return "manage/manage-result";
    }
}
